'use strict';

const Controller = require('egg').Controller;

class HomeController extends Controller {
  // 分页 & 列表
  async list() {
    const { ctx } = this;


    const sql = 'select * from question';
    const results = await this.app.mysql.query(sql);

    ctx.body = {
      code: 200,
      data: results,

    };
  }


  // 加入购物车
  async shopping() {
    const { ctx } = this;
    const { user, id, img, question, data, writer } = ctx.request.body;


    // 该用户购物车中是否存在该商品

    // 存在
    const results = await this.app.mysql.select('shopping', { // 搜索 post 表
      where: {
        user_id: user,
        shop_id: id,
      }, // WHERE 条件
    });
    if (results.length) {
      // 修改数据，将会根据主键 ID 查找，并更新
      const row = {
        id: results[0].id,
        num: results[0].num + 1,
      };
      await this.app.mysql.update('shopping', row); // 更新 shopping 表中的记录
      ctx.body = {
        code: 200,
        msg: '加入成功',
      };
    } else {
      // 不存在
      const result = await this.app.mysql.insert('shopping', { user_id: user, shop_id: id, img, question, writer, data, num: 1 });
      const insertSuccess = result.affectedRows === 1;
      if (insertSuccess) {
        ctx.body = {
          code: 200,
          msg: '加入成功！！！',
        };
      } else {
        ctx.body = {
          code: 402,
          msg: '加入失败',
        };
      }
    }


  }


  // 购物车列表
  async shopList() {
    const { ctx } = this;
    const { user } = ctx.request.body;
    const results = await this.app.mysql.select('shopping', { // 搜索 post 表
      where: { user_id: user }, // WHERE 条件
    });
    ctx.body = {
      code: 200,
      data: results,
    };
  }
}

module.exports = HomeController;
